package com.greateamd.timetableasy.client.widgets.user;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.greateamd.timetableasy.client.services.user.UserService;
import com.greateamd.timetableasy.client.services.user.UserServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.client.widgets.LabelizableListBox;
import com.greateamd.timetableasy.domain.User;

public class TeacherListBox extends LabelizableListBox 
{
	private List<User> teachers = new ArrayList<User>();
	
	public @UiConstructor TeacherListBox(boolean autoLoad,boolean multi) {
		super(multi);
		if(autoLoad){
			loadTeacher();
		}
	}	

	public void loadTeacher() {
		final UserServiceAsync userService = GWT.create(UserService.class);
		new ServerCall<List<User>>() {

			@Override
			protected void callService(AsyncCallback<List<User>> asyncCallback) {
				userService.getAllTeachers(asyncCallback);
			}

			@Override
			public void onSuccess(List<User> users) {
				teachers = users;
				showListTeacher();
			}
		}.call();
	}

	protected void showListTeacher() {
		clear();
		for(User user : teachers){
			addItem(user.getUsername());
		}
	}
	
	public void selectTeacher(User teacher){
		int pos = teachers.indexOf(teacher);
		if(pos > -1)
			setSelectedIndex(pos);
	}
	
	public User getSelectedUser(){
		if(getSelectedIndex() > -1 && getSelectedIndex() <= teachers.size())
			return teachers.get(getSelectedIndex());
		return null;
	}
}
